package org.privat24.api.misc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author dezmond
 */
public class TransferUtil {
    
    
    public TransferUtil(){
        HttpsSecurityUtil.allowHttpsCertificates();
    }

    protected void sendRequest(URLConnection connection, String requestXML) throws UnsupportedEncodingException, IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.append(requestXML);
        writer.flush();
    }

    protected String receiveResponse(URLConnection connection) throws IOException {
        StringBuilder responseBuilder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        for (String line; (line = reader.readLine()) != null;) {
            responseBuilder.append(line);
        }

        return responseBuilder.toString();
    }
    
    
    public String getResponseXML(String requestXML, String requestUrl) throws IOException{

        HttpURLConnection connection = (HttpURLConnection) new URL(requestUrl).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setAllowUserInteraction(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "text/xml;charset=\"utf-8\"");
        connection.setRequestProperty("Accept", "text/xml");
        connection.setRequestProperty("Content-length",""+requestXML.length());
        
        sendRequest(connection, requestXML);
        return receiveResponse(connection); 
        
    }

    
    public String changeEncoding(String from, String to, String description) {
        try {
            return new String(description.trim().getBytes(from),to);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(TransferUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
     
}